import time
import uuid
from xtquant.xttrader import XtQuantTrader
from xtquant.xttype import StockAccount
from QMT import MyXtQuantTraderCallback
from 主程.基础配置 import settings
from threading import Lock
from 组件.notice import show_notification_thread, init_notification_system
import traceback


class QMTTrader:
    def __init__(self):
        self.callback = None
        self._lock = Lock()
        self.running = False
        self.path = settings.QMT_DIR
        self.session_id = None  # 延迟生成session_id
        self.acc = StockAccount(settings.ACC, 'STOCK')
        self.xt_trader = None  # 延迟初始化，在 start() 中创建
        self.log_callback = None  # 新增日志

    def set_log_callback(self, callback):
        self.log_callback = callback

    def start(self):
        """启动交易系统"""
        with self._lock:
            if self.running:
                print("交易系统已经在运行中")
                return True
            
            print('开始连接交易账户...')
            
            # 生成唯一的session_id
            self.session_id = int(time.time() * 1000) + hash(str(uuid.uuid4())) % 1000
            
            # 创建新的 xt_trader 实例
            try:
                self.xt_trader = XtQuantTrader(self.path, self.session_id)
                self.callback = MyXtQuantTraderCallback(self,self.acc, self.xt_trader)
                self.xt_trader.register_callback(self.callback)
                self.xt_trader.start()  # 启动交易线程
            except Exception as e:
                print(f"创建交易实例失败: {e}")
                self._cleanup()
                return False

            # 连接交易账户
            if not self._connect_trader():
                self._cleanup()
                return False

            self.running = True
            return True

    def _connect_trader(self):
        """连接交易账户（同步版本）"""
        try:
            if self.xt_trader.connect() != 0:
                print("交易连接失败")
                show_notification_thread("系统", "QMT初始化失败")
                return False

            if self.xt_trader.subscribe(self.acc) != 0:
                print("交易订阅失败")
                return False

            print("交易系统连接成功")
            show_notification_thread("系统", "QMT初始化完成")
            return True
        except Exception as e:
            print(f"连接交易账户时出错: {e}")
            return False

    def stop(self):
        """停止程序"""
        with self._lock:
            if not self.running:
                return
            self.running = False

        self._cleanup()
        print("程序已安全退出")

    def _cleanup(self):
        """清理资源"""
        try:
            # 首先清理回调对象，防止新的回调执行
            if hasattr(self, 'callback') and self.callback:
                # 清空回调中的trader引用，防止访问已销毁的对象
                if hasattr(self.callback, 'trader'):
                    self.callback.trader = None
                if hasattr(self.callback, 'xt_trader'):
                    self.callback.xt_trader = None
                self.callback = None
                
            # 停止交易接口
            if self.xt_trader is not None:
                try:
                    # 先取消订阅
                    if hasattr(self.xt_trader, 'unsubscribe'):
                        self.xt_trader.unsubscribe(self.acc)
                    # 然后停止
                    self.xt_trader.stop()
                except Exception as e:
                    print(f"停止交易时出错: {e}")
                finally:
                    self.xt_trader = None
                    
            # 清理其他资源
            self.session_id = None
            self.log_callback = None
            
        except Exception as e:
            print(f"清理资源时出错: {e}")
            traceback.print_exc()

    def is_running(self):
        """检查是否正在运行"""
        with self._lock:
            return self.running


if __name__ == "__main__":
    trader = QMTTrader()
    try:
        if trader.start():
            print("交易启动成功，按 Ctrl+C 停止...")
            while True:  # 主循环保持运行
                time.sleep(1)
    except KeyboardInterrupt:
        print("\n用户中断，停止交易...")
        trader.stop()